<template>
  <div class="lottery-container">
    <h1>幸运大抽奖</h1>

    <div class="tabs">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{
          active: activeTab === index,
          winner: isDrawing && finalWinnerIndex === index,
        }"
      >
        {{ tab.rulePrize }}
        <span v-if="finalWinnerIndex === index" class="prize-icon">🎁</span>
      </button>
    </div>

    <button class="draw-btn" @click="startDraw" :disabled="isDrawing">
      {{ isDrawing ? "抽奖中..." : "开始抽奖" }}
    </button>

    <div v-if="finalWinnerIndex !== null" class="result">
      <h3>
        {{ "恭喜您抽到了：" + tabs[finalWinnerIndex].ruleName }}
      </h3>
      <p>{{ "奖品：" + tabs[finalWinnerIndex].rulePrize }}</p>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ElMessage } from "element-plus";
import { ref } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
let prizeReq = route.query;

const activeTab = ref(0);
const isDrawing = ref(false);
const finalWinnerIndex = ref(null);

const tabs = ref([]);

const startDraw = () => {
  if (tabs.value.length === 0) {
    ElMessage.warning("暂无抽奖规则，请稍后再试");
    return;
  }

  isDrawing.value = true;
  finalWinnerIndex.value = null;

  // 抽奖动画效果 - 快速切换tab
  let counter = 0;
  const totalSwitches = 30; // 切换次数
  const switchInterval = setInterval(() => {
    activeTab.value = (activeTab.value + 1) % tabs.value.length;
    counter++;

    // 最后几次减慢速度
    if (counter > totalSwitches - 10) {
      clearInterval(switchInterval);
      slowDownDraw();
    }
  }, 100);
};

const getRuleByActivityId = (prizeReq) => {
  axios
    .post("/api/activity/getRuleByUserId", prizeReq)
    .then((res) => {
      if (res.data.code === 200) {
        tabs.value = res.data.data;
        // 确保概率总和不超过100%
        validateProbabilities();
      } else {
        ElMessage.error(res.data.msg || "查询失败");
      }
    })
    .catch((error) => {
      ElMessage.error("获取抽奖规则失败");
      console.error(error);
    });
};
getRuleByActivityId(prizeReq);

// 验证概率总和不超过100%
const validateProbabilities = () => {
  const total = tabs.value.reduce(
    (sum, tab) => sum + Number(tab.prizeProbability),
    0
  );
  if (total > 100) {
    ElMessage.warning("警告:奖品概率总和超过100%，请检查配置");
  }
};

const slowDownDraw = () => {
  let slowCounter = 0;
  const slowSwitches = 10;
  const slowInterval = setInterval(() => {
    activeTab.value = (activeTab.value + 1) % tabs.value.length;
    slowCounter++;

    if (slowCounter >= slowSwitches) {
      clearInterval(slowInterval);
      finishDraw();
    }
  }, 200);
};

const finishDraw = () => {
  // 计算总概率（正常情况下应该是100，但做兼容处理）
  const totalProbability = tabs.value.reduce(
    (sum, tab) => sum + Number(tab.prizeProbability),
    0
  );

  // 生成0-100之间的随机数
  const random = Math.random() * 100;

  let accumulatedProbability = 0;

  for (let i = 0; i < tabs.value.length; i++) {
    accumulatedProbability += Number(tabs.value[i].prizeProbability);

    if (random < accumulatedProbability) {
      finalWinnerIndex.value = i;
      activeTab.value = i;
      break;
    }
  }

  // 如果因为概率总和不足100%而没有选中任何奖项
  if (finalWinnerIndex.value === null && tabs.value.length > 0) {
    finalWinnerIndex.value = 0; // 默认选中第一个
    activeTab.value = 0;
  }

  isDrawing.value = false;

  // 抽奖完成后再记录日志
  if (finalWinnerIndex.value !== null) {
    addLotteryLog();
  }
};

const addLotteryLog = () => {
  axios
    .post("/api/activity/addLotteryLog", {
      ruleName: tabs.value[finalWinnerIndex.value].ruleName,
      rulePrize: tabs.value[finalWinnerIndex.value].rulePrize,
    })
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success("已记录");
      } else {
        ElMessage.error(res.data.msg || "添加失败");
      }
    });
};
</script>

<style scoped>
.lottery-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  text-align: center;
  font-family: "Arial", sans-serif;
}

h1 {
  color: #e74c3c;
  margin-bottom: 30px;
}

.tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.tabs button {
  padding: 12px 20px;
  margin: 0 5px 10px;
  background-color: #f8f9fa;
  border: 2px solid #ddd;
  border-radius: 30px;
  font-size: 16px;
  font-weight: bold;
  color: #555;
  cursor: default;
  transition: all 0.3s;
  position: relative;
}

.tabs button.active {
  border-color: #e74c3c;
  color: #e74c3c;
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(231, 76, 60, 0.3);
}

.tabs button.winner {
  background-color: #e74c3c;
  color: white;
  border-color: #e74c3c;
  animation: pulse 1.5s infinite;
}

.prize-icon {
  margin-left: 5px;
}

.draw-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 15px 40px;
  font-size: 18px;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.draw-btn:hover {
  background-color: #c0392b;
  transform: scale(1.05);
}

.draw-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
  transform: none;
}

.result {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 10px;
  margin-top: 20px;
  animation: fadeIn 0.5s;
}

.result h3 {
  color: #e74c3c;
  margin-bottom: 10px;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
